import { UIUtils } from '../utils/ui.js';

export class FormController {
    constructor() {
        this.initializeFormHandlers();
        this.setupResponsiveLayout();
    }

    initializeFormHandlers() {
        // 为所有表单添加提交事件处理
        document.querySelectorAll('form').forEach(form => {
            form.addEventListener('submit', this.handleFormSubmit.bind(this));
            
            // 为必填字段添加实时验证
            form.querySelectorAll('[required]').forEach(field => {
                field.addEventListener('blur', this.handleFieldValidation.bind(this));
                field.addEventListener('input', this.handleFieldValidation.bind(this));
            });
        });
    }

    setupResponsiveLayout() {
        // 监听窗口大小变化
        window.addEventListener('resize', this.handleResponsiveLayout.bind(this));
        // 初始化时执行一次
        this.handleResponsiveLayout();
    }

    handleResponsiveLayout() {
        const isMobile = window.innerWidth < 768;
        document.body.classList.toggle('mobile-view', isMobile);
        
        // 调整表单布局
        document.querySelectorAll('.form-group').forEach(group => {
            if (isMobile) {
                group.classList.add('flex-column');
                group.classList.remove('row');
            } else {
                group.classList.remove('flex-column');
                group.classList.add('row');
            }
        });
    }

    async handleFormSubmit(event) {
        event.preventDefault();
        const form = event.target;
        
        // 使用 UIUtils 进行表单验证
        if (UIUtils.validateForm(form)) {
            const loading = UIUtils.showLoading('正在保存...');
            try {
                const formData = new FormData(form);
                const response = await fetch(form.action, {
                    method: form.method || 'POST',
                    body: formData
                });
                
                const result = await response.json();
                if (result.success) {
                    UIUtils.showToast('保存成功', 'success');
                    // 根据需要重定向或刷新页面
                    if (result.redirect) {
                        window.location.href = result.redirect;
                    }
                } else {
                    UIUtils.showToast(result.error || '保存失败', 'error');
                }
            } catch (error) {
                console.error('表单提交失败:', error);
                UIUtils.showToast('系统错误，请稍后重试', 'error');
            } finally {
                UIUtils.hideLoading(loading);
            }
        }
    }

    handleFieldValidation(event) {
        const field = event.target;
        const value = field.value.trim();
        const validationMessage = this.getValidationMessage(field, value);
        
        // 更新字段的验证状态
        field.classList.toggle('is-invalid', !!validationMessage);
        field.classList.toggle('is-valid', !validationMessage && value);
        
        // 更新或创建反馈消息元素
        let feedback = field.nextElementSibling;
        if (!feedback || !feedback.classList.contains('invalid-feedback')) {
            feedback = document.createElement('div');
            feedback.className = 'invalid-feedback';
            field.parentNode.insertBefore(feedback, field.nextSibling);
        }
        feedback.textContent = validationMessage || '';
    }

    getValidationMessage(field, value) {
        if (field.hasAttribute('required') && !value) {
            return '此字段为必填项';
        }
        
        if (field.type === 'email' && value && !this.isValidEmail(value)) {
            return '请输入有效的电子邮件地址';
        }
        
        if (field.type === 'number') {
            const min = field.getAttribute('min');
            const max = field.getAttribute('max');
            const num = Number(value);
            
            if (value && isNaN(num)) {
                return '请输入有效的数字';
            }
            if (min && num < Number(min)) {
                return `数值不能小于 ${min}`;
            }
            if (max && num > Number(max)) {
                return `数值不能大于 ${max}`;
            }
        }
        
        // 自定义验证规则
        if (field.dataset.pattern) {
            const pattern = new RegExp(field.dataset.pattern);
            if (value && !pattern.test(value)) {
                return field.dataset.patternMessage || '输入格式不正确';
            }
        }
        
        return '';
    }

    isValidEmail(email) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }
}

// 初始化表单控制器
document.addEventListener('DOMContentLoaded', () => {
    window.formController = new FormController();
}); 